<?php
include_once "lib/wxBizMsgCrypt.php";
include_once "document/randomResponse.php";

// 企业号在公众平台上设置的参数 
define("ENCODINGAESKEY","Cj0EyzxaM4JRcQmb396MDzT3lsdlRMbUbXrQxmy5KgW");
define("TOKEN","lwh");
define("CORPID","wx751e041cdef857d6");

//wenjianlujing
define('ROOT_PATH','/var/www/php/');

$wechatObj = new wechatCallback();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $wechatObj->responseMsg();
}

class wechatCallback{

	private $wxcpt;

	//gouzaohanshu
	public function __construct(){
		// 企业号在公众平台上设置的参数 
		$encodingAesKey = ENCODINGAESKEY;  
		$token = TOKEN;  
		$corpId = CORPID; 
		$this->wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $corpId); 
	}

	//接口回调验证
	public function valid(){

		//设置utf-8应该是最最最关键的一步  
		header("Content-Type:text/html; charset=utf-8");

		$sVerifyMsgSig = $_GET['msg_signature'];  
		$sVerifyTimeStamp = $_GET['timestamp'];  
		$sVerifyNonce = $_GET['nonce'];    
		$sVerifyEchoStr = $_GET['echostr'];
		  
		//配置内容的格式  
		header('content-type:text');  

		//需要返回的明文
		$sEchoStr = "";
		$errCode = $this->wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);

		if ($errCode == 0) {  
			// 验证URL成功，将sEchoStr返回    
			echo $sEchoStr;  
		} 
		else {  
			print("ERR:the error code is:  " . $errCode . "\n\n");  
		}
	}

	public function responseMsg(){

		$input = file_get_contents("php://input"); //接收POST数据

		if(!empty($input)){
            $sVerifyMsgSig = $_GET['msg_signature'];
            $sVerifyTimeStamp = $_GET['timestamp'];
            $sVerifyNonce = $_GET['nonce'];

            $decryptedMsg = "";
            //解密传输过来的信息
            $errCode = $this->wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $input, $decryptedMsg);

            file_put_contents(ROOT_PATH."input.xml",$decryptedMsg.PHP_EOL);
            $xml = simplexml_load_string($decryptedMsg); //提取POST数据为simplexml对象
            $RX_TYPE = trim($xml->MsgType);
            switch($RX_TYPE){
                case "event":
                    $result = $this->receiveEvent($xml);
                    break;
                case "text":
                    $result = $this->receiveText($xml);
                    break;
            }
            //加密返回的信息并输出
            $errCode = $this->wxcpt->EncryptMsg($result, $sVerifyTimeStamp, $sVerifyNonce,$encryResult);
            echo $encryResult;
        }
        else{
		    echo "";
		    exit;
        }
	}

    private function receiveText($object){
        $content = "";
	    if( $object->Content == "1" ){
            $content = "<a href='http://118.178.94.215/register.php?userId=".$object->FromUserName."'>请点击该链接进行注册</a>";
        } else if( $object->Content == "2"){
            $content = "<a href='http://118.178.94.215/bind.php?userId=".$object->FromUserName."'>请点击该链接绑定用户名密码</a>";
        } else {
            $temp = new RandomResponse();
            $content = $temp->getRandomResponse();
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }

	private function receiveEvent($object){
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":   //关注事件
                $content = "欢迎关注CrowdFrame微信公众号。<a href='http://118.178.94.215/bind.php?userId=".$object->FromUserName."'>请点击该链接绑定用户名密码，以便后续使用</a>。
(<a href='http://118.178.94.215/register.php?userId=".$object->FromUserName."'>如果还未注册，请点击该链接进行注册</a>)";
                break;
            case "unsubscribe": //取消关注事件
                $content = "";
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 回复文本消息
     */
    private function transmitText($object, $content)
    {
        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }
}  
 
?>  
